//
//  IndexViewController.m
//  MobileStudy
//
//  Created by cuihongbao on 13-6-27.
//  Copyright (c) 2013年 hongbao.cui. All rights reserved.
//

#import "IndexViewController.h"
#import "ApplicationUtils.h"
#import "Sqlite.h"
@interface IndexViewController ()<UITableViewDataSource,UITableViewDelegate>{
    NSMutableArray *questionDoArray;
}
@property(nonatomic,strong)NSMutableArray *questionDoArray;
@end

@implementation IndexViewController
@synthesize dataDict;
@synthesize dataArray;
@synthesize questionDoArray;
@synthesize paper_idDict;
@synthesize delegate;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
-(void)meneBtnClicked:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)initNavigationBar{
    self.navigationItem.title = @"答题卡";
    //self.navigationItem.title = @"试卷测试";
    UIButton *menueButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [menueButton setFrame:CGRectMake(0, 0, 29, 29)];
    [menueButton setBackgroundImage:[ApplicationUtils getLocalImage:@"paper_question_list_normal"] forState:UIControlStateNormal];
    [menueButton setBackgroundImage:[ApplicationUtils getLocalImage:@"paper_question_list_pressed"] forState:UIControlStateHighlighted];
    [menueButton addTarget:self action:@selector(meneBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *menueBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:menueButton];
    self.navigationItem.rightBarButtonItem= menueBarButtonItem;
}
-(void)initTableView{
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, FMSCREENWIDTH, [UIScreen mainScreen].bounds.size.height-20-44) style:UITableViewStylePlain];
    [tableView setSeparatorColor:[UIColor colorWithPatternImage:[ApplicationUtils getLocalImage:@"m_card_anser005"]]];
    [tableView setDelegate:self];
    [tableView setDataSource:self];
    [self.view addSubview:tableView];
}
- (void)viewDidLoad
{
//    float systemVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
//    if (systemVersion >= 7.0)
//    {
//        //某个仅支持7.0以上版本的方法
//        self.edgesForExtendedLayout = UIRectEdgeNone;
//        
//    }
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self initNavigationBar];
    [self initTableView];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
//    if (IS_STUDY) {
//        
//    }else{
//        self.navigationController.navigationBarHidden = NO;
//    }
    [ttableView reloadData];
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
//    if (IS_STUDY) {
//        
//    }else{
//        self.navigationController.navigationBarHidden = YES;
//    }
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)dealloc{
    if (self.dataDict) {
        self.dataDict = nil;
    }
    if (self.dataArray) {
        self.dataArray = nil;
    }
    if (self.questionDoArray) {
        self.questionDoArray = nil;
    }
    if (self.paper_idDict) {
        self.paper_idDict = nil;
    }
    if (self.delegate) {
        self.delegate=nil;
    }
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.dataDict) {
        NSArray *array = [self.dataDict objectForKey:@"questions"];
        if ([array count]>0) {
            return[array count];
        }
    }
    return 0;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    if (self.dataDict) {
        NSArray *array = [self.dataDict objectForKey:@"questions"];
        NSArray *_dataArray = nil;
        if ([array count]>0) {
            _dataArray = [array objectAtIndex:section];
        }
        NSInteger count = [_dataArray count];
        int lineNumbers = 0;
        if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
            lineNumbers = 12;
        }else{
            lineNumbers = 4;
        }
        if (count%lineNumbers) {
             return count/lineNumbers+1;
        }else{
            return count/lineNumbers;
        }
    }
    return 0;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (self.dataDict) {
        NSArray *array = [self.dataDict objectForKey:@"questions"];
        if ([array count]>0) {
            NSString *titleStr = [[[array objectAtIndex:section] objectAtIndex:0] objectForKey:@"qtype_name"];
            return titleStr;
        }
    }
    return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger row = indexPath.row;
    NSInteger  section = indexPath.section;
    NSString *CellIdentifier =[NSString stringWithFormat:@"%d%d",row,section];
    UITableViewCell*cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"myCell"];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    }
    if (self.dataDict) {
        NSArray *array = [self.dataDict objectForKey:@"questions"];
        NSArray *_dataArray = [array objectAtIndex:section];
//        NSInteger count;// 选择题的个数
        float x,y;
        int index;
        int lineNumbers;
        if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
            lineNumbers = 12;
        }else{
            lineNumbers = 4;
        }
        index = row*lineNumbers;
        int allCount =[_dataArray count];
        for (int i=0; (index+i)<allCount&&i<lineNumbers; i++) {
            x=42+(30+30)*(i%lineNumbers); y=7.5;
            UIButton *bigBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            NSString *indexStr = [NSString stringWithFormat:@"%d",index+i];
            FMSCHBLog(@"--------section---------%@",indexStr);
//            NSString *indexStr= [[_dataArray objectAtIndex:(index+i)] objectForKey:@"orderid"];
            [bigBtn setTitle:[NSString stringWithFormat:@"%d",index+i+1] forState:UIControlStateNormal];
            [bigBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [bigBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
            [bigBtn setBackgroundImage:[ApplicationUtils getLocalImage:@"m_card_picture003"] forState:UIControlStateNormal];
            [bigBtn setBackgroundImage:[ApplicationUtils getLocalImage:@"m_card_picture002"] forState:UIControlStateSelected];
            [bigBtn setFrame:CGRectMake(x, y, 30, 30)];
//            if (section==0) {
//                count = [indexStr intValue];
//                [bigBtn setTag:count];
//                NSDictionary  *dataDict_=[_dataArray objectAtIndex:count];
//                NSString *user_answer = [dataDict_ objectForKey:@"user_answer"];
//                FMSCHBLog(@"====index+i======%d",index+i);
//                if ([user_answer isEqualToString:@""]||[user_answer isEqualToString:@"(null)"]) {
//                    [bigBtn setSelected:NO];
//                }else{
//                    [bigBtn setSelected:YES];
//                }
//            }else if(section ==1){
//                NSArray *dataArray_ = [array objectAtIndex:0];
//                count = [dataArray_ count]+[indexStr intValue];
//                [bigBtn setTag:count];
//                NSDictionary  *dataDict_=[_dataArray objectAtIndex:index+i];
//                NSString *user_answer = [dataDict_ objectForKey:@"user_answer"];
//                FMSCHBLog(@"====index+i======%d",index+i);
//                if ([user_answer isEqualToString:@""]||[user_answer isEqualToString:@"(null)"]) {
//                    [bigBtn setSelected:NO];
//                }else{
//                    [bigBtn setSelected:YES];
//                }
//            }else if (section==2){
//                NSArray *singleArray_0 = [array objectAtIndex:0];
//                NSArray *selectArray = [array objectAtIndex:1];
//                count = [singleArray_0 count]+[selectArray count]+[indexStr integerValue];
//                [bigBtn setTag:count];
//                NSDictionary  *dataDict_=[_dataArray objectAtIndex:index+i];
//                NSString *user_answer = [dataDict_ objectForKey:@"user_answer"];
//                if ([user_answer isEqualToString:@"正确"]) {
//                    [bigBtn setSelected:YES];
//                }else if([user_answer isEqualToString:@"错误"]){
//                    [bigBtn setSelected:YES];
//                }
////                if ([user_answer isEqualToString:@""]) {//针对简答题，没做呢，
////                    [bigBtn setSelected:NO];
////                }else{
////                    [bigBtn setSelected:YES];
////                }
//            }else if (section == 3){
//                NSArray *singleArray_0 = [array objectAtIndex:0];
//                NSArray *singleArray_1 = [array objectAtIndex:1];
//                NSArray *selectArray = [array objectAtIndex:2];
//                count = [singleArray_0 count]+[singleArray_1 count]+[selectArray count]+[indexStr integerValue];
//                [bigBtn setTag:count];
//            }else{
//                NSInteger count1=0;
//                for (NSInteger j=0; j<section; j++) {
//                    count1 += [[array objectAtIndex:j] count];
//                }
//                count1 +=[indexStr integerValue];
//                [bigBtn setTag:count1];
//            }
            NSInteger count1=0;
            for (NSInteger j=0; j<section; j++) {
                count1 += [[array objectAtIndex:j] count];
            }
            count1 +=[indexStr integerValue];
            [bigBtn setTag:count1];
            //针对简单题
            NSDictionary  *dataDict_=[_dataArray objectAtIndex:index+i];
            NSString *user_answer = [dataDict_ objectForKey:@"user_answer"];
            NSString *qtype = [dataDict_ objectForKey:@"qtype"];
            if ([qtype isEqualToString:@"3"]) {
                if ([user_answer isEqualToString:@"正确"]) {
                    [bigBtn setSelected:YES];
                }else if([user_answer isEqualToString:@"错误"]){
                    [bigBtn setSelected:YES];
                }
            }else if ([qtype isEqualToString:@"0"]){
                NSString *userAnswerImage = [dataDict_ objectForKey:@"userAnswerImage"];
                if ([userAnswerImage isEqualToString:@"0"]) {
                    if ([user_answer isEqualToString:@""]||[user_answer isEqualToString:@"(null)"]) {
                        [bigBtn setSelected:NO];
                    }else{
                        [bigBtn setSelected:YES];
                    }
                }else{
                    if ([user_answer hasSuffix:@"png"]) {//针对简答题,没做呢，
                        [bigBtn setSelected:YES];
                    }else{
                        [bigBtn setSelected:NO];
                    }
                }
            }else{//一般的选择，出判断外
                if ([user_answer isEqualToString:@""]||[user_answer isEqualToString:@"(null)"]) {
                    [bigBtn setSelected:NO];
                }else{
                    [bigBtn setSelected:YES];
                }
            }
            [bigBtn addTarget:self action:@selector(indexBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
            [bigBtn setBackgroundColor:[UIColor clearColor]];
            [cell.contentView addSubview:bigBtn];
        }
        
    }
    return cell;
}
-(void)indexBtnClicked:(UIButton *)sender{
    if (delegate&&[delegate respondsToSelector:@selector(IndexBtnClicked:)]) {
        [self.navigationController popViewControllerAnimated:YES];
        [delegate IndexBtnClicked:sender];
    }
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    
}
//-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    //    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
//    //    UILabel *label = (UILabel *)[cell viewWithTag:100];
//    //    int w= label.frame.size.width;
//    //    int h= label.frame.size.height;
//    //    int y =(cell.frame.size.height -label.frame.size.height)/2;
//    //    FMSCHBLog(@"cell.frame.size.height:%f",cell.frame.size.height);
//    //    FMSCHBLog(@"label.frame.size.height:%f",label.frame.size.height);
//    //    CGRect rect = CGRectOffset(CGRectMake(0, y, w, h), 2, 2);
//    //    label.frame = rect;
//    //    return label.frame.size.height;
//    NSDictionary *dataDict = [self.dataList objectAtIndex:indexPath.row];
//    NSString *text = [dataDict objectForKey:@"name"];
//    CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
//    CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
//    CGFloat height = MAX(size.height, 50.0f);
//    return height + (CELL_CONTENT_MARGIN * 2);
//}

// Override to support conditional editing of the table view.
// - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
// {
// // Return NO if you do not want the specified item to be editable.
//     return YES;
// }
//

/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
 {
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
 }
 else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }
 }
 */

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
 {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}
@end
